﻿package {
	import flash.external.ExternalInterface;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	public class PopupFromFlash {
		public static function init(){
			if(ExternalInterface.available){	// make sure the page is setup to handle the safari 'else' case:
				ExternalInterface.addCallback('openWindowFromSwf', function(pageUrl:String){
					navigateToURL(new URLRequest(pageUrl), '_blank');	// just open the link in a normal new window.
				});	// call the 'openWindow' flash function
			}
		}
		public static function popup(pageUrl:String, swfID:String, options:Object = null):void{ 
			options.windowTitle = (options.windowTitle) ? options.windowTitle : '';
			options.windowParams = (options.windowParams) ? options.windowParams : '';
				// what's the point of using a random seed? if you continually pop up windows with the same window title, the browser will re-use the same popup - but if the title is different, it'll keep popping up new windows. yes, you can use this for spamming, if you're a douche.
			options.useRandomSeed = (options.useRandomSeed!='append'&&options.useRandomSeed!=false&&options.useRandomSeed!=true) ? false : options.useRandomSeed; // interpret the incoming random seed parameter - if it's not what it expects, default to false
			if(ExternalInterface.available){	// if we can do this thing
					// tell the javascript instance of PopupFromFlash to run the openWindow function, and pass in the variables
				ExternalInterface.call('popupFromFlash.openWindow', swfID, pageUrl, options.windowTitle, options.useRandomSeed, encodeParams(options.windowParams));
			}
		}
		private static function encodeParams(params:*):String{
			var paramsString:String;
			if(params is String){paramsString = params;}else{	// if it's already a string, don't mess with it, otherwise...
				paramsString = new String();
					// loop through the params object, translating it into the format that window.open expects
				for(var i in params){paramsString += (i + '=' + params[i] + ',');}
				paramsString = paramsString.substring(0,paramsString.length-1);	// erase the trailing comma
			}
			return paramsString;	// and give back the finish params string to be sent off to window.open
		}
	}
}